package com.uuzuche.lib_zxing.activity;

import java.io.IOException;
import java.util.Locale;
import java.util.Vector;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.uuzuche.lib_zxing.R;
import com.uuzuche.lib_zxing.bean.ZxingConfig;
import com.uuzuche.lib_zxing.common.Constant;
import com.uuzuche.lib_zxing.decoding.CameraManager;
import com.uuzuche.lib_zxing.decoding.CaptureActivityHandler;
import com.uuzuche.lib_zxing.decoding.DecodeImgCallback;
import com.uuzuche.lib_zxing.decoding.DecodeImgThread;
import com.uuzuche.lib_zxing.decoding.FinishListener;
import com.uuzuche.lib_zxing.decoding.ImageUtil;
import com.uuzuche.lib_zxing.decoding.InactivityTimer;
import com.uuzuche.lib_zxing.decoding.ViewfinderView;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import static android.app.Activity.RESULT_OK;

/**
 * 自定义实现的扫描Fragment
 */
public class CaptureFragment extends Fragment implements SurfaceHolder.Callback, View.OnClickListener {

    private static final String TAG = CaptureFragment.class.getSimpleName();

    private CaptureActivityHandler handler;

    private ViewfinderView viewfinderView;

    private boolean hasSurface;

    private Vector<BarcodeFormat> decodeFormats;

    private String characterSet;

    private InactivityTimer inactivityTimer;

    private MediaPlayer mediaPlayer;

    private boolean playBeep;

    private static final float BEEP_VOLUME = 0.10f;

    private boolean vibrate;

    private SurfaceView surfaceView;

    private SurfaceHolder surfaceHolder;

    private CodeUtils.AnalyzeCallback analyzeCallback;

    public ZxingConfig config;

    private ImageView flashLightIv;

    private TextView flashLightTv;

    private ImageView backIv;

    private LinearLayoutCompat flashLightLayout;

    private LinearLayoutCompat albumLayout;

    private LinearLayoutCompat bottomLayout;

    private CameraManager cameraManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        String centertext =getActivity().getString(R.string.res_failed);
//        String res_ok =getActivity().getString(R.string.res_ok);
//        String res_title =getActivity().getString(R.string.res_title);
//        com.uuzuche.lib_zxing.utils.AlertDialog myDialog = new com.uuzuche.lib_zxing.utils.AlertDialog(getActivity()).builder();
//        myDialog.setGone().setTitle(res_title).setMsg(centertext).setPositiveButton(res_ok, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                isGoOn=true;
//            }
//        }).show();
        /* 先获取配置信息 */
        try {
            config = (ZxingConfig) getActivity().getIntent().getExtras().get(Constant.INTENT_ZXING_CONFIG);
            Intent intent = getActivity().getIntent();
            String locale = intent.getStringExtra("locale");
            Resources resources = getActivity().getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config2 = resources.getConfiguration();
            System.out.println("########:" + config2.locale);
            if (locale != null && locale.equals("简体")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    config2.setLocale(Locale.SIMPLIFIED_CHINESE);
                }
                else {
                    config2.locale = Locale.SIMPLIFIED_CHINESE;
                }
            }
            else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    config2.setLocale(Locale.TRADITIONAL_CHINESE);
                }
                else {
                    config2.locale = Locale.TRADITIONAL_CHINESE;
                }
            }

            resources.updateConfiguration(config2, dm);
            // 将图片路径photoPath传到所要调试的模块
            System.out.println("########222:" + config2.locale);
            String sss = getActivity().getString(R.string.scan_code);
            System.out.println("######444:" + sss);

        }
        catch (Exception e) {

            Log.i("config", e.toString());
        }

        if (config == null) {
            config = new ZxingConfig();
        }

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this.getActivity());

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {

        Bundle bundle = getArguments();
        View view = null;
        if (bundle != null) {
            int layoutId = bundle.getInt(CodeUtils.LAYOUT_ID);
            if (layoutId != -1) {
                view = inflater.inflate(layoutId, null);
            }
        }

        if (view == null) {
            view = inflater.inflate(R.layout.activity_capture2, null);
        }

        viewfinderView = view.findViewById(R.id.viewfinder_view);
        String centertext =getActivity().getString(R.string.centertext);
        viewfinderView.setCenterText(centertext);
        viewfinderView.setZxingConfig(config);
        surfaceView = view.findViewById(R.id.preview_view);
        surfaceHolder = surfaceView.getHolder();

        flashLightTv = view.findViewById(R.id.flashLightTv);
        flashLightIv = view.findViewById(R.id.flashLightIv);

        backIv = view.findViewById(R.id.backIv);
        backIv.setOnClickListener(this);

        flashLightLayout = view.findViewById(R.id.flashLightLayout);
        flashLightLayout.setOnClickListener(this);
        albumLayout = view.findViewById(R.id.albumLayout);
        albumLayout.setOnClickListener(this);
        bottomLayout = view.findViewById(R.id.bottomLayout);

        switchVisibility(bottomLayout, config.isShowbottomLayout());
        switchVisibility(flashLightLayout, config.isShowFlashLight());
        switchVisibility(albumLayout, config.isShowAlbum());

        flashLightLayout.setVisibility(View.VISIBLE);

        // /*有闪光灯就显示手电筒按钮 否则不显示*/
        //
        // if (isSupportCameraLedFlash(getActivity().getPackageManager())) {
        // flashLightLayout.setVisibility(View.VISIBLE);
        // } else {
        // flashLightLayout.setVisibility(View.GONE);
        // }

        return view;
    }

    /**
     * @param pm
     * @return 是否有闪光灯
     */
    public static boolean isSupportCameraLedFlash(PackageManager pm) {
        if (pm != null) {
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            if (features != null) {
                for (FeatureInfo f : features) {
                    if (f != null && PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param flashState 切换闪光灯图片
     */
    public void switchFlashImg(int flashState) {

        if (flashState == Constant.FLASH_OPEN) {
            flashLightIv.setImageResource(R.drawable.ic_open);
            flashLightTv.setText(R.string.close_flash);
        }
        else {
            flashLightIv.setImageResource(R.drawable.ic_close);
            flashLightTv.setText(R.string.open_flash);
        }

    }

    private void switchVisibility(View view, boolean b) {
        if (b) {
            view.setVisibility(View.VISIBLE);
        }
        else {
            view.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getActivity(), config);

        viewfinderView.setCameraManager(cameraManager);

        if (hasSurface) {
            initCamera(surfaceHolder);
        }
        else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getActivity().getSystemService(getActivity().AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        // beepManager.close();
        cameraManager.closeDriver();

        if (!hasSurface) {

            surfaceHolder.removeCallback(this);
        }
    }

    @Override
    public void onDestroy() {
        inactivityTimer.shutdown();
        viewfinderView.stopAnimator();
        super.onDestroy();
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        String centertext =getActivity().getString(R.string.scan_code);
        builder.setTitle(centertext);
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton(R.string.button_ok, new FinishListener(getActivity()));
        builder.setOnCancelListener(new FinishListener(getActivity()));
        builder.show();
    }


    boolean  isGoOn=true;
    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        if(isGoOn){
            isGoOn=false;
            inactivityTimer.onActivity();
            playBeepSoundAndVibrate();

            if (result == null || TextUtils.isEmpty(result.getText())) {
                //            if (analyzeCallback != null) {
                //                analyzeCallback.onAnalyzeFailed();
                //            }
                // res_failed
                String centertext =getActivity().getString(R.string.res_failed);
                String res_ok =getActivity().getString(R.string.res_ok);
                String res_title =getActivity().getString(R.string.res_title);
                com.uuzuche.lib_zxing.utils.AlertDialog myDialog = new com.uuzuche.lib_zxing.utils.AlertDialog(getActivity()).builder();
                myDialog.setGone().setTitle(res_title).setMsg(centertext).setPositiveButton(res_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isGoOn=true;
                    }
                }).show();

            }
            else {
                if (analyzeCallback != null) {
                    Intent intent = getActivity().getIntent();
                    String h5 = intent.getStringExtra("h5");
                    if(h5!=null){
                        String res=result.getText();
                        String[] ress=res.split(",");
                        if(ress.length==3){
                            analyzeCallback.onAnalyzeSuccess(barcode, result.getText());
                            isGoOn=true;
                        }else{

                            String centertext =getActivity().getString(R.string.res_failed);
                            String res_ok =getActivity().getString(R.string.res_ok);
                            String res_title =getActivity().getString(R.string.res_title);
                            com.uuzuche.lib_zxing.utils.AlertDialog myDialog = new com.uuzuche.lib_zxing.utils.AlertDialog(getActivity()).builder();
                            myDialog.setGone().setTitle(res_title).setMsg(centertext).setPositiveButton(res_ok, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    isGoOn=true;
                                }
                            }).show();
                        }
                    }else{
                        analyzeCallback.onAnalyzeSuccess(barcode, result.getText());
                        isGoOn=true;
                    }

                }
            }
        }

    }

    private void initCamera(SurfaceHolder surfaceHolder) {

        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            if (callBack != null) {
                callBack.callBack(null);
            }
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, decodeFormats, characterSet, viewfinderView);
                // handler = new CaptureActivityHandler(getActivity(), cameraManager);

            }
        }
        catch (IOException ioe) {
            displayFrameworkBugMessageAndExit();
        }
        catch (RuntimeException e) {
            displayFrameworkBugMessageAndExit();
        }

    }

    @Override
    public void onClick(View view) {

        int id = view.getId();
        if (id == R.id.flashLightLayout) {
            /* 切换闪光灯 */
            if (!isSupportCameraLedFlash(getActivity().getPackageManager())) {
                Toast.makeText(getActivity(),getString(R.string.flash_failed),Toast.LENGTH_LONG).show();
            }else{
                cameraManager.switchFlashLight(handler);
            }
        }
        else if (id == R.id.albumLayout) {
            /* 打开相册 */
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, Constant.REQUEST_IMAGE);
        }
        else if (id == R.id.backIv) {
            getActivity().finish();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            }
            catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constant.REQUEST_IMAGE && resultCode == RESULT_OK) {
            String path = ImageUtil.getImageAbsolutePath(getActivity(), data.getData());

            new DecodeImgThread(path, new DecodeImgCallback() {
                @Override
                public void onImageDecodeSuccess(Result result) {
                    handleDecode(result, null);
                }

                @Override
                public void onImageDecodeFailed() {
                    Toast.makeText(getActivity(), R.string.scan_failed_tip, Toast.LENGTH_SHORT).show();
                }
            }).run();

        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    public CodeUtils.AnalyzeCallback getAnalyzeCallback() {
        return analyzeCallback;
    }

    public void setAnalyzeCallback(CodeUtils.AnalyzeCallback analyzeCallback) {
        this.analyzeCallback = analyzeCallback;
    }

    @Nullable
    CameraInitCallBack callBack;

    /**
     * Set callback for Camera check whether Camera init success or not.
     */
    public void setCameraInitCallBack(CameraInitCallBack callBack) {
        this.callBack = callBack;
    }

    interface CameraInitCallBack {
        /**
         * Callback for Camera init result.
         * 
         * @param e If is's null,means success.otherwise Camera init failed with the Exception.
         */
        void callBack(Exception e);
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void setCameraManager(CameraManager cameraManager) {
        this.cameraManager = cameraManager;
    }
}
